<?php
namespace app\common\service\merchant;
use app\common\cache\merchant\MerchantRechargeCache;
use app\common\model\Merchant\MerchantAccountModel;
use app\common\model\Merchant\MerchantRechargeModel;
use app\common\model\setting\SettingCollectionModel;
use think\facade\Db;
/**
 * 商家充值记录
 */
class MerchantRechargeService
{
    /**
     * 添加、修改字段
     * @var array
     */
    public static $edit_field = [
            'id' => '',
        'is_disable' => '',
        'merchant_id' => '',
        'amount' => '',
        'setting_collection_code' => '',
        'setting_collection_id' => '',
        'merchant_account_id' => '',
        'z_account' => '',
        'z_name' => '',
        'voucher_id' => '',
        'bank_card' => '',
        'payee_name' => '',
        'payee_image_id' => '',
        'payee_card' => '',
        'payee_bank' => '',
        'transaction_no' => '',
        'auth_status' => '',
        'auth_msg' => '',
        'type' => '',
        'remark' => '',
    ];
    /**
     * 商家充值记录列表
     *
     * @param array  $where 条件
     * @param int    $page  页数
     * @param int    $limit 数量
     * @param array  $order 排序
     * @param string $field 字段
     *
     * @return array
     */
    public static function list($where = [], $page = 1, $limit = 10,  $order = [], $field = '')
    {
        $model = new MerchantRechargeModel();
        $pk = $model->getPk();
        if (empty($field)) {
            $field = 'id,is_disable,create_time,update_time,merchant_id,amount,setting_collection_code,setting_collection_id,merchant_account_id,z_account,z_name,voucher_id,bank_card,payee_name,payee_image_id,payee_card,payee_bank,transaction_no,auth_status,auth_msg,type,remark,principal_balance,commission_balance';
        }
        if (empty($order)) {
            $order = [$pk => 'desc'];
        }
        $with = $append = $hidden = [];
        if (strpos($field, 'voucher_id') !== false) {
            $with[]   = $hidden[] = 'voucher';
            $append[] = 'voucher_url';
        }
        if (strpos($field, 'payee_image_id') !== false) {
            $with[]   = $hidden[] = 'payee';
            $append[] = 'payee_url';
        }
        if ($page == 0 || $limit == 0) {
            return $model->with($with)->append($append)->hidden($hidden)->field($field)->where($where)->order($order)->select()->toArray();
        }
        $count = $model->where($where)->count();
        $pages = ceil($count / $limit);
        $list = $model->with($with)->append($append)->hidden($hidden)->field($field)->where($where)->page($page)->limit($limit)->order($order)->select()->toArray();
        foreach ($list as $key=>$val){
            $list[$key]['setting_collection_title'] = SettingCollectionModel::getPayType($val['setting_collection_code'],1);
        }
        return compact('count', 'pages', 'page', 'limit', 'list');
    }
    /**
     * 商家充值记录信息
     *
     * @param int  $id   商家充值记录id
     * @param bool $exce 不存在是否抛出异常
     *
     * @return array|Exception
     */
    public static function info($id, $exce = true)
    {
        $info = MerchantRechargeCache::get($id);
        if (empty($info)) {
            $model = new MerchantRechargeModel();
            $info = $model->find($id);
            if (empty($info)) {
                if ($exce) {
                    exception('商家充值记录不存在：' . $id);
                }
                return [];
            }
            $info = $info->toArray();
            MerchantRechargeCache::set($id, $info);
        }
        return $info;
    }
    /**
     * 商家充值记录添加
     *
     * @param array $param 商家充值记录信息
     *
     * @return array|Exception
     */
    public static function add($param)
    {
        $model = new MerchantRechargeModel();
        $pk = $model->getPk();
        unset($param[$pk]);
        //查询收款信息
        $collectionModel = new SettingCollectionModel();
        $collection = $collectionModel->where('id',$param['setting_collection_id'])
            ->where('is_disable',0)
            ->where('is_delete',0)
            ->order(['sort'=>'asc','id' => 'desc'])
            ->find();
        if(!$collection){
            exception("充值方式不存在1");
        }
        //查询商家余额
        $mer_money = Db::name('merchant')->where('id',mer_id())->field('id,mer_money,mer_commission')->find();
        //充值信息
        $data = array(
            'merchant_id'=>mer_id(),//商家id
            'amount'=>$param['amount'],//充值金额
            'principal_balance'=>isset($mer_money['mer_money'])?$mer_money['mer_money']:0,//本金余额
            'commission_balance'=>isset($mer_money['mer_commission'])?$mer_money['mer_commission']:0,//佣金余额
            'setting_collection_code'=>$collection['code'],//充值方式编码(OnLineAlipay:在线支付宝,Alipay：支付宝，WeChat：微信，Card：银行卡)
            'setting_collection_id'=>$collection['id'],//充值方式
            'merchant_account_id'=>null,//商户充值账户id(支付宝/银行卡)
            'z_account'=>null,//转账账户
            'z_name'=>null,//转账姓名
            'voucher_id'=>null,//转账凭证id
            'bank_card'=>null,//转账银行卡号
            'payee_name'=>$collection['name'],//收款人姓名
            'payee_image_id'=>$collection['image_id'],//收款码
            'payee_card'=>$collection['account'],//收款银行卡号
            'payee_bank'=>$collection['card_bank'],//收款开户行
            'transaction_no'=>null,//交易单号
            'auth_status'=>0,//审核状态：0、待审核 1、审核通过 2、审核拒绝
            'type'=>1,//充值类型：1、本金充值 2、佣金充值
            'create_uid'=>mer_user_id(),//添加用户id
            'create_time'=>date('Y-m-d H:i:s'),//创建时间
        );
        //充值凭证
        if($collection['code']!='OnLineAlipay'){
            if(!isset($param['voucher_id']) || !$param['voucher_id']){
                exception('请上传支付凭证');
            }else{
                $data['voucher_id']=$param['voucher_id'];
            }
        }
        //验证
        switch ($collection['code']){
            case 'OnLineAlipay':
                //支付宝账号
                if(!isset($param['merchant_account_id']) || !$param['merchant_account_id']){
                    exception('请选择支付宝账号');
                }
                $merchant_account = MerchantAccountModel::where('id',$param['merchant_account_id'])
                    ->where('is_disable',0)
                    ->where('is_delete',0)
                    ->where('merchant_id',mer_id())
                    ->field('id,alipay_account')
                    ->find();
                if(!$merchant_account){
                    exception('支付宝账号不存在');
                }
                $data['merchant_account_id'] =$merchant_account['id'];
                $data['z_account'] =$merchant_account['alipay_account'];
                break;
            case 'Alipay':
                //支付宝
                if(!isset($param['z_account']) || !$param['z_account']){
                    exception('请输入支付订单号后6位');
                }
//                if(!isset($param['z_name']) || !$param['z_name']){
//                    exception('请输入付款支付宝姓名');
//                }
                $data['z_account'] =$param['z_account'];
                $data['z_name'] =$param['z_name'];
                break;
            case 'WeChat':
                //微信
                break;
            case 'Card':
                //银行卡
                if(!isset($param['merchant_account_id']) || !$param['merchant_account_id']){
                    exception('请选择银行卡');
                }
                $merchant_account = MerchantAccountModel::where('id',$param['merchant_account_id'])
                    ->where('is_disable',0)
                    ->where('is_delete',0)
                    ->where('merchant_id',mer_id())
                    ->field('id,card_no,name')
                    ->find();
                if(!$merchant_account){
                    exception('银行卡不存在');
                }
                $data['merchant_account_id'] =$merchant_account['id'];
                $data['bank_card'] =$merchant_account['card_no'];
                $data['z_account'] =$merchant_account['card_no'];
                $data['z_name'] =$merchant_account['name'];
                break;
        }
        $model->save($data);
        $id = $model->$pk;
        if (empty($id)) {
            exception();
        }
        $data[$pk] = $id;
        return $data;
    }
     /**
     * 商家充值记录修改
     *
     * @param int|array $ids   商家充值记录id
     * @param array     $param 商家充值记录信息
     *
     * @return array|Exception
     */
    public static function edit($ids, $param = [])
    {
        $model = new MerchantRechargeModel();
        $pk = $model->getPk();
        unset($param[$pk], $param['ids']);
        $param['update_uid']  = user_id();
        $param['update_time'] = datetime();
        $res = $model->where($pk, 'in', $ids)->update($param);
        if (empty($res)) {
            exception();
        }
        $param['ids'] = $ids;
        MerchantRechargeCache::del($ids);
        return $param;
    }
    /**
     * 商家充值记录删除
     *
     * @param array $ids  商家充值记录id
     * @param bool  $real 是否真实删除
     *
     * @return array|Exception
     */
    public static function dele($ids, $real = false)
    {
        $model = new MerchantRechargeModel();
        $pk = $model->getPk();
        if ($real) {
            $res = $model->where($pk, 'in', $ids)->delete();
        } else {
            $update = delete_update();
            $res = $model->where($pk, 'in', $ids)->update($update);
        }
        if (empty($res)) {
            exception();
        }
        $update['ids'] = $ids;
        MerchantRechargeCache::del($ids);
        return $update;
    }

    /**
     * 审核
     * @Author: 易军辉
     * @DateTime:2024-07-12 14:16
     * @param $ids
     * @param $param
     * @return array|mixed
     * @throws \think\Exception
     */
    public static function auth($ids, $param = [])
    {
        $model = new MerchantRechargeModel();
        $pk = $model->getPk();
        unset($param[$pk], $param['ids']);
        $list = $model
            ->where('is_disable',0)
            ->where('is_delete',0)
            ->where('auth_status',0)
            ->where($pk, 'in', $ids)
            ->select();
        if(count($list)<=0){
            exception("未有符合条件的充值记录需要审核");
        }
        // 启动事务
        $model->startTrans();
        try {
            foreach ($list as $k=>$v){
                $v->auth_time=datetime();
                $v->auth_uid=user_id();
                switch (intval($param['auth_status'])){
                    case 0://待审核
                        $v->auth_status=0;
                        break;
                    case 1://审核通过
                        $v->auth_status=1;
                        $title = SettingCollectionModel::getPayType($v['setting_collection_code'],1);
                        //待审核
                        $consumption_res = MerchantService::recharge(
                            $v['merchant_id'],
                            $v['amount'],
                            $v['amount'],
                            0,
                            $title.'充值',
                            $v['id'],
                            "充值记录ID：".$v['id']
                        );
                        break;
                    case 2://审核未通过
                        $v->auth_status=2;
                        $v->auth_msg=$param['auth_msg'];
                        break;
                }
                $v->save();
            }
            // 提交事务
            $model->commit();
        } catch (\Exception $e) {
            $errmsg = $e->getMessage();
            // 回滚事务
            $model->rollback();
        }

        if (isset($errmsg)) {
            exception($errmsg);
        }

        $param['ids'] = $ids;
        MerchantRechargeCache::del($ids);
        return $param;
    }

    /**
     * 查询充值方式
     * @Author: 易军辉
     * @DateTime:2024-07-15 16:36
     * @return array[]
     */
    public static function getRechargeTyps()
    {
        return SettingCollectionModel::PAY_TYPES;
    }
}
